﻿using System;
using System.ComponentModel;
using System.Runtime.Remoting.Messaging;

namespace TouchHelpers.Helper
{
    public class TwitterHelper
    {
        
        #region Obsolete
        //private const string ConsumerKey = "2JAShmxJgMHlzOMb75kupg";
        //private const string ConsumerSecret = "nmin3dSLfCdNkZALv9MekfYmnH5u7HIASUUZS1RUU";

        //public string GetLoginUrl()
        //{
        //    var requestToken = FluentTwitter.CreateRequest().Authentication.GetRequestToken(ConsumerKey, ConsumerSecret, CallBackUrl);

        //    var response = requestToken.Request();
        //    var request = response.AsToken();

        //    var authentication = FluentTwitter.CreateRequest().Authentication;
        //    var authorizeUrl = authentication.GetAuthorizationUrl(request.Token);
        //    return authorizeUrl;
        //}

        //public void Authenticate(string authToken, string verifier)
        //{
        //    AccessToken = GetAccessToken(AuthToken, verifier);
        //    var query = FluentTwitter.CreateRequest().AuthenticateWith(ConsumerKey, ConsumerSecret, AccessToken.Token, AccessToken.TokenSecret).Account().VerifyCredentials().AsXml();

        //    var response = query.Request();
        //}

        //private OAuthToken GetAccessToken(string requestToken, string verifier)
        //{
        //    var accessToken = FluentTwitter.CreateRequest()
        //        .Authentication.GetAccessToken(ConsumerKey, ConsumerSecret, requestToken, verifier);

        //    var response = accessToken.Request();
        //    var result = response.AsToken();

        //    if (result == null)
        //    {
        //        var error = response.AsError();
        //        if (error != null)
        //        {
        //            throw new Exception(error.ErrorMessage);
        //        }
        //    }

        //    return result;
        //}

        //public string AuthToken { get; set; }
        //public OAuthToken AccessToken { get; set; }

        //public string CallBackUrl { get; set; }

        //public void UploadPicture(string filePath, string userName, string password)
        //{
        //    var twipli = new TwiPLi.TwitPicLib(userName,password);
        //    twipli.UploadAndPost(filePath,"Picture from MTouch");
        //}
        #endregion

        private delegate void TwitterUploadDelegate(string filePath, string userName, string password, string message);
        public event AsyncCompletedEventHandler TwitterPictureUploaded;
        private Exception _exception;

        public void UploadPictureAsync(string filePath, string userName, string password, string message)
        {
            TwitterUploadDelegate worker = TwitterUploadWorker;
            AsyncCallback completedCallback = TwitterUploadCompleteCallback;
            var async = AsyncOperationManager.CreateOperation(null);
            worker.BeginInvoke(filePath, userName, password, message, completedCallback, async);
        }

        private void TwitterUploadWorker(string filePath, string userName, string password, string message)
        {
            message = "From MTouch - " + message;
            _exception = null;
            var twipli = new TwiPLi.TwitPicLib(userName, password);
            var result = twipli.UploadAndPost(filePath, message);
            if(result.ErrorCode!=0)
            {
                _exception = new Exception(result.ErrorMessage);
            }
        }

        private void TwitterUploadCompleteCallback(IAsyncResult ar)
        {
            var worker = (TwitterUploadDelegate)((AsyncResult)ar).AsyncDelegate;
            var async = (AsyncOperation)ar.AsyncState;
            worker.EndInvoke(ar);
            var completedArgs = new AsyncCompletedEventArgs(_exception, false, null);
            async.PostOperationCompleted(e => OnTwitterPictureUploaded((AsyncCompletedEventArgs) e), completedArgs);
        }

        private void OnTwitterPictureUploaded(AsyncCompletedEventArgs asyncCompletedEventArgs)
        {
            if (TwitterPictureUploaded != null)
                TwitterPictureUploaded(this, asyncCompletedEventArgs);
        }

        public object Data { get; set; }
    }
}
